package com.white.androidhistoryechoes

import android.R
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.View
import android.view.WindowManager
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.view.marginTop
import com.google.android.material.datepicker.MaterialDatePicker
import com.white.androidhistoryechoes.databinding.ActivityMainBinding
import com.white.androidhistoryechoes.view.activty.HistoryEchoesDetailActivity
import com.white.androidhistoryechoes.view.adapter.HistoryEchoesAdapter
import com.white.androidhistoryechoes.viewmodel.MainViewModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding
    private val mainViewModel: MainViewModel by viewModels()
    private val adapter = HistoryEchoesAdapter()
    private var selectedDateTime = System.currentTimeMillis()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val simpleDateFormat = SimpleDateFormat("MM月dd日", Locale.getDefault())
        val currentDate = simpleDateFormat.format(Date())
        binding.tvDate.text = currentDate
        adapter.setOnItemHistoryEchosClickListener { view, model ->
            HistoryEchoesDetailActivity.start(this, model.id)
        }
        binding.rvHistoryEchoes.adapter = adapter
        mainViewModel.getHistoryEchoesList(binding.tvDate.text.toString())
        mainViewModel.historyEchoesListLiveData.observe(this) {
            Log.i("TAG", "it: ${it}")
            adapter.mData = it
        }

        binding.tvDate.setOnClickListener {
            showDatePickerDialog()
        }
    }

    private fun showDatePickerDialog() {
        val picker = MaterialDatePicker.Builder.datePicker()
            .setTitleText("选择日期")
            .setSelection(selectedDateTime)
            .build()
        picker.addOnPositiveButtonClickListener {
            val simpleDateFormat = SimpleDateFormat("MM月dd日", Locale.getDefault())
            val selectDate = simpleDateFormat.format(Date(it))
            mainViewModel.getHistoryEchoesList(selectDate)
            selectedDateTime = it
            binding.tvDate.text = selectDate
        }
        picker.show(supportFragmentManager, "DATA_PICKER")
    }
}